package com.aruba.bulethoothdemoapplication.utils.printer;

import android.os.Handler;
import android.os.Message;

import com.aruba.bulethoothdemoapplication.utils.livedatabus.LiveDataBus;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 打印交接单和患者知情同意书的打印机
 * Created by xuqiwei on 19-12-13.
 */

public enum ShiftAndInformedPrinter implements Handler.Callback, PrinterTool.PrinterToolListener {
    instance;
    private ExecutorService countDownService;
    private Handler disconnectHandler;
    private ShiftPrinterTool printerTool;
    private int delayTime = 10;

    ShiftAndInformedPrinter() {
        disconnectHandler = new Handler(this);
        countDownService = Executors.newFixedThreadPool(2);
    }

    public void startPrint(String deviceAddress, List<PrintStuff> printList, int delayTime) throws PrinterException {
        this.delayTime = delayTime;
        if (printerTool == null) {
            printerTool = new ShiftPrinterTool(this);
        }
        printerTool.setAddress(deviceAddress);
        String blueToothAddress = DataConvertUtils.nullCheck(printerTool.getAddress());
        if ("".equals(blueToothAddress)) {
            throw new PrinterException("还没有配置蓝牙地址！请到设置页面配置。");
        }
        printerTool.setPrinter(printList);
        printerTool.start();
    }

    @Override
    public boolean handleMessage(Message message) {
        if (printerTool != null) {
            printerTool.destroy();
        }
        printerTool = null;
        LiveDataBus.getInstance().with(PrinterStatus.EVENT_KEY, PrinterStatus.class).setValue(new PrinterStatus("打印完成,正在断开连接..."));
        return false;
    }

    @Override
    public void onStartPrint() {
        countDownService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(delayTime * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                disconnectHandler.sendEmptyMessage(0);

            }
        });
    }


    private class ShiftPrinterTool extends PrinterTool {
        String address = "";

        public ShiftPrinterTool(PrinterToolListener listener) {
            super(listener);
        }

        public void setAddress(String deviceAddress) {
            address = deviceAddress;
        }

        @Override
        public String getAddress() {
            return address;
        }
    }

}
